package com.users.rn.kit.bridge.impl.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.users.rn.kit.bridge.RNBridgeModuleName
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.users.rn.kit.RNKITTools

/**

 * 作者：wolf on 1/17/21 16:36

 * 邮箱：bluce

 */

class KitBroadcastEmitter(val context: ReactApplicationContext) : ReactContextBaseJavaModule(context) {
    override fun getName(): String {
        return KitBroadcastEmitter::class.java.simpleName
    }

    private var receive: BroadcastReceiver? = null

    override fun initialize() {
        super.initialize()
        receive = object : BroadcastReceiver() {
            override fun onReceive(mContext: Context?, intent: Intent?) {
                if (intent != null) {
                    val eventName =
                        intent.getStringExtra(RNBridgeModuleName.RN_JS_BROADCAST_FILTER_NAME)
                    val content = intent.getStringExtra(RNBridgeModuleName.RN_JS_BROADCAST_CONTENT)
                    if (eventName != null) {
                        context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
                            .emit(eventName, content)
                    }
                }
            }
        }
        receive?.let {
            LocalBroadcastManager.getInstance(context.applicationContext)
                .registerReceiver(
                    receive as BroadcastReceiver,
                    IntentFilter(RNBridgeModuleName.RN_JS_BROADCAST)
                )
        }
    }

    override fun onCatalystInstanceDestroy() {
        super.onCatalystInstanceDestroy()
        receive?.let {
            LocalBroadcastManager.getInstance(context)
                .unregisterReceiver(it)
        }
    }

    @ReactMethod
    fun sendBroadcast(eventName: String, content: String) {
        RNKITTools.sendBroadcast(context, eventName, content)
    }
}